package com.seantone.umeng_link.umeng_link_flutter;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;

import com.google.gson.Gson;
import com.umeng.umlink.MobclickLink;
import com.umeng.umlink.UMLinkListener;

import java.util.HashMap;

import io.flutter.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.ActivityLifecycleListener;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;

/** UmengLinkFlutterPlugin */
public class UmengLinkFlutterPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.NewIntentListener {
  Activity mActivity = null;
  boolean isInit = false;
  HashMap<String,String> mQueryParams = null;
  public static  OneLinkCallback mOneLinkCallBack = null;

  UMLinkListener umlinkAdapter =new UMLinkListener(){
    @Override
    public void onLink(String path,HashMap<String,String> query_params){
      if(0 == query_params.size()) return;
      if(mOneLinkCallBack != null)
      {
        mOneLinkCallBack.onMessage(new Gson().toJson(query_params));
      }else{
        mQueryParams = query_params;
      }
    }

    @Override
    public void onInstall(HashMap<String,String> install_params, Uri uri){
      if(0 == install_params.size()) return;
      if(mOneLinkCallBack != null)
      {
        mOneLinkCallBack.onMessage(new Gson().toJson( install_params));
      }else{
        mQueryParams =  mQueryParams;
      }
    }

    @Override
    public void onError(String error){

    }
  };


  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;

  //=============================传递消息到flutter的Event事件======================================
  // 事件派发对象
  private  EventChannel.EventSink eventSink = null;
  // 事件派发流
  private  EventChannel.StreamHandler streamHandler = new  EventChannel.StreamHandler(){
    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
      eventSink = events;
    }

    @Override
    public void onCancel(Object arguments) {
      eventSink = null;
    }
  };
  EventChannel eventChannel = null;
  void sendFlutterEvent(){
    // 初始化事件
//        EventChannel eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_show_alert/event");
//        eventChannel.setStreamHandler(streamHandler);
  }
  //==============================================================================


  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "umeng_link_flutter");
    channel.setMethodCallHandler(this);

    eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), "umeng_link_flutter_event");
    eventChannel.setStreamHandler(streamHandler);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("init")) {
      isInit = true;
      if(mActivity != null){
        MobclickLink.handleUMLinkURI(mActivity, mActivity.getIntent().getData(), umlinkAdapter);
        MobclickLink.getInstallParams(mActivity, false, umlinkAdapter);
      }

      result.success( null);
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
    eventChannel.setStreamHandler(null);
  }

  @Override
  public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
    binding.addOnNewIntentListener(this);
    mActivity = binding.getActivity();
    mOneLinkCallBack = message -> {
      if(  eventSink != null){
        eventSink.success(message);
      }
    };
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {
    mActivity = null;
  }

  @Override
  public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
    mActivity = binding.getActivity();
    binding.addOnNewIntentListener(this);
  }

  @Override
  public void onDetachedFromActivity() {
    mActivity = null;
  }

  @Override
  public boolean onNewIntent(@NonNull Intent intent) {
    if(isInit) {
      MobclickLink.handleUMLinkURI(mActivity, intent.getData(), umlinkAdapter);
    }
    return false;
  }
}
